﻿/* 7. Sorting an array means to arrange its elements in increasing order. 
 * Write a program to sort an array. 
 * Use the "selection sort" algorithm:  Find the smallest element, 
 *                                      move it at the first position, 
 *                                      find the smallest from the rest, 
 *                                      move it at the second position,
 *                                      etc. */

using System;

public class SelectionSortAlgorithm
{
    public static double[] array;

    public static void Main()
    {
        if (0 < DataInput())
        {
            PrintArray(array);
            SelectionSort(array);
            PrintArray(array);
            Console.WriteLine();
        }
        else
            Console.WriteLine("\nThe length of array must be natural!\n");
    }

    public static int DataInput()
    {
        int n;

        Console.Write("\nThe length of array: ");
        n = int.Parse(Console.ReadLine());

        if (0 < n)
        {
            array = new double[n];

            Console.WriteLine();
            for (int i = 0; i < n; i++)
            {
                Console.Write("Array[{0}] = ", i);
                array[i] = double.Parse(Console.ReadLine());
            }
        }

        return n;
    }

    public static void PrintArray(double[] array)
    {
        Console.Write("\n {0} {1}", "{", array[0]);
        for (int i = 1; i < array.Length; i++)
            Console.Write(", {0}", array[i]);

        Console.WriteLine(" {0}", "}");
    }

    public static void SelectionSort(double[] array)
    {
        int indexOfCurrentMinElement;

        for (int i = 0; i < array.Length; i++)
        {
            indexOfCurrentMinElement = i;
            for (int j = i + 1; j < array.Length; j++)
                if (array[j] < array[indexOfCurrentMinElement])
                    indexOfCurrentMinElement = j;

            if (indexOfCurrentMinElement != i)
                Swap(array, i, indexOfCurrentMinElement);
        }
    }

    public static void Swap(double[] array, int i, int j)
    {
        double temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}